//
//  MeatMapShopAddressViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/8/2.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatMapShopAddressViewController.h"
#import "AddressInputViewController.h"
#import "MeatSearchHeader.h"
#import "MeatTipLabel.h"
#import "MeatMapLocationView.h"
#import "MeatMapFooter.h"
#import "MeatMapTableViewCell.h"
#import "MeatSearchAreaView.h"
#import "MeatSearchAddressView.h"


@interface MeatMapShopAddressViewController ()

@property (nonatomic, strong) UIButton *rightNav;
@property (nonatomic, strong) MeatTipLabel *tipLabel;
@property (nonatomic, strong) MeatMapLocationView *locationView;
@property (nonatomic, strong) MeatSearchAddressView *searchHeader;
@property (nonatomic, strong) MeatSearchAreaView *searchAreaView;

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *ranges;
@property (nonatomic, strong) NSArray *sections;
@property (nonatomic, strong) NSArray *locations; //当前维度
@property (nonatomic, assign) CGFloat keyboardHeight;


@end

@implementation MeatMapShopAddressViewController

#pragma mark - lifecycle methods

- (void)setupUI
{
    [self tribeRangeRequest];

    {
        self.baseNavView.navTitleLabel.text = @"选择配送范围";
        self.baseNavView.line.hidden = YES;
        self.view.backgroundColor = KWhiteColor;
        
        [self.baseNavView.rightNavBtn setTitle:@"新增地址" forState:UIControlStateNormal];
        self.baseNavView.rightNavBtn.hidden = NO;
        self.baseNavView.rightNavBtn.width = 65;
        self.baseNavView.rightNavBtn.mj_x = KScreenWidth - self.baseNavView.rightNavBtn.width -5;
        
        @weakify(self);
        self.baseNavView.rightBlock = ^{
            @strongify(self);
            
            AddressInputViewController *addressInputVC = [[AddressInputViewController alloc] init];
            addressInputVC.title = AddAddressTitle;
            [self.navigationController pushViewController:addressInputVC animated:YES];

        };
    }
    
    {
        [self.view addSubview:self.searchHeader];
        [self.view addSubview:self.tipLabel];

        self.searchAreaView.hidden = YES;
        [self.view addSubview:self.searchAreaView];
    }
    
}


- (void)setupLayout
{
    {
        self.reloadBtn.mj_y += 30;
        self.reloadLab.mj_y += 30;
    }

    {
        _searchHeader.mj_y = TJ_NavBarHeight;
    }
    
    {
        _tipLabel.mj_y = _searchHeader.bottom + 3;
    }
    
    {
        self.tableView.mj_y = _tipLabel.bottom;
        self.tableView.height = KScreenHeight - (_tipLabel.bottom);
    }
    
    {
        self.searchAreaView.frame = CGRectMake(0, TJ_StatusBarHeight_Define, KScreenWidth, KScreenHeight - TJ_StatusBarHeight_Define);

    }
}


#pragma mark - networking methods

- (void)initData {
    
    if (self.dataArr.count >0) {
        [self.dataArr removeAllObjects];
    }
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getAddressListWithMemberId:memberId] subscribeNext:^(AddressList * _Nullable addressList) {
        @strongify(self);

        [self.dataArr addObjectsFromArray:addressList.list];
        if (self.isRefresh) {
            [self endRefresh];
        }
        
        if (self.dataArr.count >0) {
            self.tableView.hidden = NO;
            [self localReloadTableViewBySection:0];
        }else{
            [self loadNoData];
        }
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}

//下拉刷新
- (void)refresh
{
    [super refresh];
    [self resetData];
    [self initData];
    [self tribeRangeRequest];
}

//配送范围数据请求
- (void)tribeRangeRequest {
    
    if (self.ranges.count >0) {
        [self.ranges removeAllObjects];
    }
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] getTribeRange] subscribeNext:^(TribeRangeList * _Nullable tribeRangeList) {
        @strongify(self);
        [self.ranges addObjectsFromArray:tribeRangeList.list];
        [self obtainLocations];
    }];
}

- (void)obtainLocations
{
    LocationManager *locationManager = [LocationManager sharedManager];
    [locationManager manageSearchNearByLocation];
    
    @weakify(self);
    
    locationManager.locationSearchBlock = ^(NSArray *locations) {
        
        @strongify(self);
        [locations enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [locations enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                AMapPOI *mapPOI = (AMapPOI*) obj;
                [self.ranges enumerateObjectsUsingBlock:^(id  _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
                    TribeRange *range = (TribeRange *)item;
                    
                    [range.raglist enumerateObjectsUsingBlock:^(LongAndLat * _Nonnull location, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        if ((mapPOI.location.latitude <= [location.latitude floatValue])
                            && (mapPOI.location.longitude <= [location.longitude floatValue])) {
                            
                            mapPOI.hasIndoorMap = YES;
                        }else{
                            mapPOI.hasIndoorMap = NO;
                        }
                        
                    }];
                }];
            }];
            
            self.locations = locations;
            [self localReloadTableViewBySection:1];
        }];
        
    };
        
    
    locationManager.locationNameBlock = ^(NSString *location, double latitude, double longitude) {
        @strongify(self);
        
        self.locationView.locationLab.text = location;
        
        __block BOOL isHaveLocation = NO;
        [self.ranges enumerateObjectsUsingBlock:^(id  _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
            TribeRange *range = (TribeRange *)item;
            
            [range.raglist enumerateObjectsUsingBlock:^(LongAndLat * _Nonnull location, NSUInteger idx, BOOL * _Nonnull stop) {
                
                
                if ((latitude <= [location.latitude floatValue])
                    && (longitude <= [location.longitude floatValue])) {
                    
                    isHaveLocation = YES;
                    return ;
                }
            }];
            
        }];
        
        if (isHaveLocation) {
            self.tipLabel.hidden = YES;
            self.tipLabel.height = 0;
        }else{
            self.tipLabel.hidden = NO;
            self.tipLabel.height = 34;
        }
        [self setupLayout];
    };
    
}

#pragma mark - tableview.delegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return section == 0 ?self.dataArr.count :self.locations.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 34;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, KScreenWidth, 34);
    view.backgroundColor = mBackgroudColor;
    
    NSString *text = self.sections[section];
    UILabel *label = [UILabel makeLabelWithText:text textColor:UIColorFromRGB(0x969696) font:mFont(14) textAliment:0];
    label.size = CGSizeMake(100, 34);
    label.mj_y = 0;
    label.mj_x = 15;
    [view addSubview:label];
    
    return view;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 68;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MeatMapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMapTableViewCell"];
    cell.isHiddenTip = indexPath.section == 0 ?NO :YES;
    
    if (indexPath.section == 0 && indexPath.row <self.dataArr.count) {
        Address *item = self.dataArr[indexPath.row];
        cell.item = item;
        cell.isHiddenRemind = YES;

    }else{
        
        if (indexPath.row < self.locations.count) {
            AMapPOI *mapPOI = _locations[indexPath.row];
            
            cell.locationLab.text = [NSString stringWithFormat:@"%@", mapPOI.name];
            cell.detailLocationLab.text = [NSString stringWithFormat:@"%@", mapPOI.address];
            cell.isHiddenRemind = mapPOI.hasIndoorMap ?NO :YES;
        }
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark - other methods

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    [self.view endEditing:YES];
//    CGFloat sectionHeaderHeight = 34;
//    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
//        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
//        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//    }
//}

#pragma mark - setter methods
#pragma mark - getter methods

- (void)registerTableViewCell{
    
    self.tableView.backgroundColor = KWhiteColor;
    self.tableView.separatorColor = mIconLineColor;
    self.tableView.rowHeight = 68;
    self.tableView.tableHeaderView = self.locationView;
    self.tableView.mj_footer.hidden = YES;
    MeatMapFooter *footer = [[MeatMapFooter alloc] init];
    self.tableView.tableFooterView = footer;
    [self.tableView registerClass:[MeatMapTableViewCell class] forCellReuseIdentifier:@"MeatMapTableViewCell"];

}


//搜索地址View
- (MeatSearchAddressView *)searchHeader
{
    if (!_searchHeader) {
        _searchHeader = [[MeatSearchAddressView alloc] init];
        
        
        kWeakSelf(self);
        //开始编辑Block
        _searchHeader.startBlock = ^{
            
            weakself.baseNavView.hidden = YES;
            weakself.searchAreaView.hidden = NO;
            weakself.searchHeader.mj_y = TJ_StatusBarHeight_Define;
            weakself.searchAreaView.mj_y = weakself.searchHeader.bottom;
        };
        
        
        //结束编辑Block
        _searchHeader.endBlock = ^{
            
            weakself.baseNavView.hidden = NO;
            weakself.searchAreaView.hidden = YES;
            
            weakself.searchHeader.mj_y = weakself.baseNavView.bottom;
        };
    }
    return _searchHeader;
    
}




- (MeatTipLabel *)tipLabel{
    if (!_tipLabel) {
        _tipLabel = [[MeatTipLabel alloc] init];
        _tipLabel.height = 34;
        _tipLabel.text = @"当前不在配送范围内，请选择您的准确地址";
    }
    return _tipLabel;
}


- (MeatMapLocationView *)locationView{
    
    if (!_locationView) {
        _locationView = [[MeatMapLocationView alloc] init];
    }
    return _locationView;
}


- (MeatSearchAreaView *)searchAreaView{
    if (!_searchAreaView) {
        CGRect rect = CGRectMake(0, 0, KScreenWidth, KScreenHeight);
        _searchAreaView = [[MeatSearchAreaView alloc]initWithFrame:rect];
        _searchAreaView.hidden = YES;
        
        @weakify(self);
        _searchAreaView.choosedCellBlock = ^(NSInteger choosedIndex, AMapTip *tip) {
            @strongify(self);
            self.searchAreaView.hidden = YES;
            [self.view endEditing:YES];
            AMapGeoPoint *location = (AMapGeoPoint *)tip.location;

            CLLocationCoordinate2D coordinate;
            coordinate.latitude = location.latitude;
            coordinate.longitude = location.longitude;

           // [self setMapRegionWithCoordinate:coordinate];

            [self.searchAreaView clearTableViewData];
            [self.searchHeader cancelDealTextField];
        };
        
        
        _searchAreaView.tapGestureBlock = ^{
            @strongify(self);
            self.searchAreaView.hidden = YES;
            [self.view endEditing:YES];
        };
        
    }
    return _searchAreaView;
}


- (NSMutableArray *)dataArr{
    
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (NSMutableArray *)ranges{
    
    if (!_ranges) {
        _ranges = [NSMutableArray array];
    }
    return _ranges;
}


- (NSArray *)locations{
    
    if (!_locations) {
        _locations = [NSArray array];
    }
    return _locations;
}

- (NSArray *)sections{
    
    if (!_sections) {
        _sections = @[@"收货地址", @"附近地址"];
    }
    return _sections;
}


#pragma mark - notification methods

- (void)keyboardWillShow:(NSNotification *)aNotification{
    
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    self.keyboardHeight = keyboardRect.size.height;
    self.searchAreaView.height = KScreenHeight - self.searchHeader.bottom - self.keyboardHeight;
    
}

- (void)keyboardWillHide:(NSNotification *)aNotification{ //当键退出时调用
    
    self.keyboardHeight = 0.0;
    self.searchAreaView.height = KScreenHeight - self.searchHeader.bottom - self.keyboardHeight;
}


- (void)textFieldTextChanged:(NSNotification *)aNotification
{
    UITextField * textField = aNotification.object;
    
    if (textField == self.searchHeader.textField) {
        
        if (textField.text.length >0) {
            
            [self.searchAreaView keywordsSearchWithKeywords:textField.text];
            
        }else{
            
            [self.searchAreaView clearTableViewData];
        }
    }
}


#pragma mark - other methods

//添加键盘通知
- (void)addNotifications{
    
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(textFieldTextChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

//移除键盘通知
- (void)removeNotifications{
    
    [kNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}


#pragma mark - override methods

- (void)loadErrorData
{
    [super loadErrorData];
    self.tipLabel.hidden = YES;
}

- (void)loadNoData
{
    [super loadNoData];
    self.tipLabel.hidden = YES;
}


- (void)endLoadMore{
    [super endLoadMore];
    self.tipLabel.hidden = NO;
    
}

- (void)endRefresh{
    [super endRefresh];
    self.tipLabel.hidden = NO;
}

- (void)endLoadMoreMoData
{
    [super endLoadMoreMoData];
    self.tipLabel.hidden = NO;
}

- (void)dealloc{
    [self showHudWithMsg:@"我解放了"];
}


@end



